/* eslint-disable no-trailing-spaces */
/* eslint-disable one-var */
// eslint-disable-next-line one-var
import request from '@/utils/request'
export function draw(can) {
  var canvas,
    boundsX, // 边界宽度
    boundsY, // 边界高度
    topPadding, // 上边界留白
    leftPadding, // 左边界留白	
    fontPadding = 5, // 字体留白
    fontSize = 14, // 字体大小
    label, // 最长label
    labelWidth, // label最大宽度
    plan, 		// 计划label
    actual, 	// 实际label
    showTime, // 显示时间段
    showTimeWidth, // 显示时间段宽度
    nowTime, // 当前时间
    leftTime, // 时间轴左侧时间
    rightTime, // 时间轴右侧时间
    timeFlagWidth, // 时间标记宽度
    timeFlagHeight, // 时间标记宽度
    drageTime, // 当前拖拽的时间标记
    drageTimeX, // 可拖动时间坐标X
    drageTimeY, // 可拖动时间坐标Y
    drageStatus = false, // 拖拽状态
    ctx,
    // 轨道的基本信息
    track = {
      num: 0,
      name: '道'
    },
    // 列车基本信息
    trains = [],
    data = {
      'items': [
        {
          'id': '37030479-12b7-4ae3-b56a-16a98fc828a2',
          'arriveName': '0D3606',
          'outSetName': null,
          'trackNum': 5,
          'arriveDate': '2018-12-28T15:55:00',
          'outSetDate': '2018-12-28T18:09:00',
          'type': null,
          'isStop': false,
          'isDelete': false
        },
        {
          'id': 'd17725a3-75dc-4050-9a4a-836fb277b419',
          'arriveName': '0D3781',
          'outSetName': null,
          'trackNum': 3,
          'arriveDate': '2018-12-28T06:11:00',
          'outSetDate': '2018-12-28T06:15:00',
          'type': null,
          'isStop': false,
          'isDelete': false
        },
        {
          'id': '52a4cd3c-d769-42e3-8398-684c2aae60cb',
          'arriveName': '0D5436',
          'outSetName': null,
          'trackNum': 1,
          'arriveDate': '2018-12-28T05:28:00',
          'outSetDate': '2018-12-28T06:00:00',
          'type': null,
          'isStop': false,
          'isDelete': false
        }       
      ],
      'count': 3
    }
  init({ trackNum: 13, showTime: 4 })
  // 初始化
  function init(option) {
    option = option || {}
    canvas = can
    if (canvas.getContext) {
      timeFlagWidth = option.timeFlagWidth || 10
      timeFlagHeight = option.timeFlagHeight || 10
      track.num = option.trackNum || 0
      showTime = option.showTime || 6
      plan = option.planLabel || '计划'
      actual = option.actualLabel || '实际'
      fontSize = option.fontSize || fontSize
      
      // 添加测试数据
      trains = data.items

      ctx = canvas.getContext('2d')
      ctx.lineWith = 2
      ctx.textBaseline = 'middle'
      ctx.font = fontSize
      topPadding = option.fontSize || 30
      leftPadding = maxLeftPadding()
      // 边界赋值
      var rect = canvas.getBoundingClientRect()
      boundsX = rect.width - leftPadding - labelWidth
      boundsY = rect.height - topPadding

      showTimeWidth = (boundsX - leftPadding - labelWidth) / showTime
      nowTime = new Date()
      drawSchedule(nowTime)

      canvas.onmousedown = function(e) {		
        if ((e.offsetX >= drageTimeX - timeFlagWidth / 2 && e.offsetX <= drageTimeX + timeFlagWidth / 2) && (e.offsetY >= drageTimeY && e.offsetY <= drageTimeY + timeFlagHeight)) {
          drageStatus = true
          console.log('mousedown: ' + e)
        }
        e.preventDefault()
      }

      canvas.onmousemove = function(e) {
        if (drageStatus) {
          var x = e.offsetX
          x = x < leftPadding + labelWidth ? leftPadding + labelWidth : x
          x = x > boundsX ? boundsX : x
          // 计算坐标差
          var diff = x - drageTimeX
          var second = Math.abs(diff) / (showTimeWidth / 60) * 60
          console.log('dif: ' + second)
          drageTime.setSeconds(diff > 0 ? drageTime.getSeconds() + second : drageTime.getSeconds() - second)

          update(drageTime)

          console.log('drageTime:' + drageTime)
        }
        e.preventDefault()
      }

      canvas.onmouseup = function(e) {
        console.log('mouseup' + e)
        drageStatus = false
        e.preventDefault()
      }

      canvas.onmouseout = function(e) {
        console.log('mouseup' + e)
        // drageStatus = false;
        e.preventDefault()
      }

      window.onmouseup = function(e) {
        if (drageStatus) {
          drageStatus = false
        }
      }
    } else {
      console.log('You browser can not support canvas!!')
    }
  }

  // 绘制计划表
  function drawSchedule(time) {
    drawTime(time)
    drawDragTimeFlag(time)
    drawTrack()
    drawTrainInfo()

    // 绘制表格边框线
    ctx.moveTo(leftPadding, boundsY)
    ctx.lineTo(boundsX, boundsY)

    ctx.stroke()
  }

  // 更新渲染
  function update(time) {
    ctx.clearRect(0, 0, canvas.width, canvas.height)
    drawSchedule(time)
  }

  // 绘制车次信息
  function drawTrainInfo() {
    for (var i = 0; i <= trains.length - 1; i++) {
      var arriveDate = new Date(trains[i].arriveDate)
      var outSetDate = new Date(trains[i].outSetDate)
      if (!(outSetDate.getHours() <= leftTime.getHours() || arriveDate.getHours() >= (rightTime.getHours() <= 0 ? 24 : rightTime.getHours()))) {
        drawTrain(trains[i].name, arriveDate, outSetDate, trains[i].trackNum, trains[i].isPlan)
      }
    }
  }
  // 绘制具体车次
  function drawTrain(name, arriveDate, outSetDate, trackNum, isPlan) {
    isPlan = isPlan || true
    // 只读取时分秒
    arriveDate.setDate(leftTime.getDate())
    outSetDate.setDate(leftTime.getDate())
    // 处理时间差
    // var hour = rightTime.getHours() - leftTime.getHours()
    var leftTimeMill = leftTime.getTime(),
      rightTimeMill = rightTime.getTime()
    // 到达坐标
    var start_x = arriveDate.getTime() <= leftTimeMill ? leftPadding + labelWidth : ((arriveDate.getTime() - leftTimeMill) / 60 / 1000) * showTimeWidth / 60 + leftPadding + labelWidth
    var start_y = (boundsY - topPadding) / track.num * (trackNum - 1) + topPadding + (boundsY - topPadding) / (track.num * 2) / 2 + (isPlan ? 0 : (boundsY - topPadding) / (track.num * 2))

    // 出发坐标
    var end_x = outSetDate.getTime() >= rightTimeMill ? boundsX : ((outSetDate.getTime() - leftTimeMill) / 60 / 1000) * showTimeWidth / 60 + leftPadding + labelWidth
    var end_y = start_y
    
    // 绘制车辆信息
    ctx.beginPath()
    // 车辆名称
    ctx.strokeText(name, start_x + (end_x - start_x) / 2 - ctx.measureText(name).width / 2, start_y - fontSize / 2)
    // 到达时间
    ctx.strokeText(arriveDate.getMinutes(), start_x - ctx.measureText(arriveDate.getMinutes()).width / 2, start_y + fontSize / 2)
    // 出发时间
    if (outSetDate.getTime() < rightTimeMill) {
      ctx.strokeText(outSetDate.getMinutes(), end_x - ctx.measureText(outSetDate.getMinutes()).width / 2, start_y + fontSize / 2)
    }

    // 绘制起始点区间
    ctx.beginPath()
    ctx.strokeStyle = '#2900ff'
    ctx.moveTo(start_x, start_y)
    ctx.lineTo(end_x, end_y)
    ctx.lineWith = 2
    ctx.stroke()

    ctx.strokeStyle = '#888'
  }	

  // 绘制拖动时间标识
  function drawDragTimeFlag(date) {
    // 处理跨天状态->23:59分之后不能显示24:00问题
    var hour = date.getDate() != nowTime.getDate() ? 24 : date.getHours(),
      minu = date.getMinutes(),
      now = date.getDate() != nowTime.getDate() ? 24 : hour,
      drawStatus = false
    // 时间区间奇偶判定
    var avgShowTime = showTime % 2 > 0 ? Math.floor(showTime / 2) : Math.ceil(showTime / 2)
    // 整天时间 - 处理边界bug
    var dayHours = showTime % 2 > 0 ? 24 : 23
    drawStatus = !!(hour <= avgShowTime || hour >= dayHours - avgShowTime)
    hour = hour <= avgShowTime ? avgShowTime + 1 : hour
    hour = hour >= dayHours - avgShowTime ? dayHours - avgShowTime : hour			

    minu = !drawStatus ? 0 : minu

    // 绘制时间
    ctx.beginPath()
    for (var i = 0, showHour = hour - Math.ceil(showTime / 2); i <= showTime; i++, showHour++) {
      // 绘制当前时间标记
      if (showHour == now) {
        ctx.fillStyle = 'red'
        // 记录当前时间点
        drageTime = new Date(date.toString())
        // 记录坐标点
        drageTimeX = showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth
        drageTimeY = boundsY

        // 绘制三角形
        ctx.moveTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth - timeFlagWidth / 2, boundsY + timeFlagHeight)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth + timeFlagWidth / 2, boundsY + timeFlagHeight)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, boundsY)			
        ctx.closePath()
        ctx.fill()
        ctx.stroke()

        // 绘制标识线
        ctx.beginPath() 
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, topPadding)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, boundsY)
        ctx.strokeStyle = 'red'
        ctx.stroke()

        ctx.strokeStyle = '#888'
      }
    }

    ctx.stroke()
  }

  // 绘制时间轴
  function drawTime(date) {
    // 处理跨天状态->23:59分之后不能显示24:00问题
    var hour = date.getDate() != nowTime.getDate() ? 24 : date.getHours(),
      minu = nowTime.getMinutes(),
      now = nowTime.getHours(),
      // 时间区间奇偶判定
      avgShowTime = showTime % 2 > 0 ? Math.floor(showTime / 2) : Math.ceil(showTime / 2)
    // 整天时间 - 处理边界bug
    var dayHours = showTime % 2 > 0 ? 23 : 24
    hour = hour < avgShowTime ? avgShowTime : hour
    hour = hour > dayHours - avgShowTime ? dayHours - avgShowTime : hour	
    // 记录时间轴两端时间
    var temTime = new Date()
    temTime.setHours(hour - avgShowTime)
    // 左侧
    leftTime = timeToHour(temTime)
    // 右侧
    temTime.setHours(hour + avgShowTime)
    rightTime = timeToHour(temTime)

    // 绘制时间
    ctx.beginPath()
    for (var i = 0, showHour = hour - avgShowTime; i <= showTime; i++, showHour++) {
      // 绘制当前时间标记
      if (showHour == now) {
        ctx.fillStyle = '#FFA500'
        // 绘制三角形
        ctx.moveTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth - timeFlagWidth / 2, topPadding - timeFlagHeight)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth + timeFlagWidth / 2, topPadding - timeFlagHeight)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, topPadding)			
        ctx.closePath()
        ctx.fill()
        ctx.stroke()

        // 绘制标识线
        ctx.beginPath() 
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, topPadding)
        ctx.lineTo(showTimeWidth * i + showTimeWidth / 60 * minu + leftPadding + labelWidth, boundsY)
        ctx.strokeStyle = '#00ff39'
        ctx.stroke()
      }
      ctx.strokeStyle = '#888'
      // 绘制时间轴标识线
      showHour = showHour < 10 ? '0' + showHour : showHour
      var width = ctx.measureText(showHour + ':00').width
      ctx.strokeText(showHour + ':00', showTimeWidth * i - width / 2 + leftPadding + labelWidth, topPadding / 2)
      ctx.moveTo(showTimeWidth * i + leftPadding + labelWidth, topPadding)
      ctx.lineTo(showTimeWidth * i + leftPadding + labelWidth, boundsY)
    }

    ctx.stroke()
  }

  // 获得最大左边界补白
  function maxLeftPadding() {
    label = ctx.measureText(plan).width > ctx.measureText(actual).width ? plan : actual
    labelWidth = ctx.measureText(label).width + fontPadding * 2
    var maxWidth = 0
    // 获得标题最大宽度
    for (var i = 0; i <= track.num - 1; i++) {
      var width = ctx.measureText(i + track.name).width
      maxWidth = maxWidth < width ? width : maxWidth
    }

    return maxWidth + 5
  }

  // 绘制轨道轴
  function drawTrack() {
    // 绘制轨道
    ctx.beginPath()
    // 绘制边框线
    ctx.moveTo(leftPadding, topPadding)
    ctx.lineTo(leftPadding, boundsY)

    for (var i = 0; i <= track.num - 1; i++) {
      // 绘制轨道label
      ctx.strokeText(i + 1 + track.name, 0, (boundsY - topPadding) / track.num * i + topPadding + (boundsY - topPadding) / track.num * 1 / 2)
      ctx.moveTo(leftPadding, (boundsY - topPadding) / track.num * i + topPadding)
      ctx.lineTo(boundsX, (boundsY - topPadding) / track.num * i + topPadding)

      // 绘制计划与实际label
      ctx.strokeText(plan, leftPadding + fontPadding, (boundsY - topPadding) / track.num * i + topPadding + (boundsY - topPadding) / (track.num * 2) / 2)
      ctx.strokeText(actual, leftPadding + fontPadding, (boundsY - topPadding) / track.num * i + topPadding + (boundsY - topPadding) / (track.num * 2) * 3 / 2)
				
      // 绘制计划与实际边线
      ctx.moveTo(leftPadding, (boundsY - topPadding) / track.num * i + topPadding + (boundsY - topPadding) / (track.num * 2))
      ctx.lineTo(boundsX, (boundsY - topPadding) / track.num * i + topPadding + (boundsY - topPadding) / (track.num * 2))
    }
    ctx.stroke()
  }

  // 具体时间转换为整点时间
  function timeToHour(date) {
    var year = date.getFullYear(),
      month = date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1,
      day = date.getDate() < 10 ? '0' + date.getDate() : date.getDate(),
      hour = date.getHours() < 10 ? '0' + date.getHours() : date.getHours()

    return new Date(year + '-' + month + '-' + day + ' ' + hour + ':00:00')
  }
}
export function getTrainInfos() {
  return request({
    url: '/getBaseInfo',
    method: 'get'   
  })
}
